package org.dbstar.scheduler.control;

import org.dbstar.scheduler.beans.Job;
import org.dbstar.scheduler.beans.MatchJobDependency;
import org.dbstar.scheduler.control.exception.DaoException;
import org.dbstar.scheduler.job.JobStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 依赖触发
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-6-13
 */
public class JobDependencyTrigger implements JobStatusChangeListener {
	private static final Logger LOGGER = LoggerFactory.getLogger(JobDependencyTrigger.class);

	private final JobDependencyController jobDependencyController;
	private final JobSchedulerExecutor jobSchedulerExecutor;

	public JobDependencyTrigger(JobController jobController, JobDependencyController jobDependencyController,
			JobSchedulerExecutor jobSchedulerExecutor) {
		super();
		this.jobDependencyController = jobDependencyController;
		this.jobSchedulerExecutor = jobSchedulerExecutor;
		// 注册监听器
		jobController.registJobStatusChangeListener(this, null, null, JobStatus.finish);
	}

	@Override
	public void onJobStatusChange(Job job, JobStatus oldStatus, JobStatus newStatus) {
		if (JobStatus.finish == newStatus) {
			try {
				for (MatchJobDependency match : jobDependencyController.findMatch(job)) {
					// 提交任务
					try {
						jobSchedulerExecutor.submit(match.getDependency().getJobConfIdentifier(), match.getParameters(), match
								.getDependency().getOwner());
					} catch (Throwable e) {
						LOGGER.error("依赖触发提交Job失败。", e);
					}
				}
			} catch (DaoException e) {
				LOGGER.error("依赖触发失败。", e);
			}
		}
	}
}
